package com.example.springbootweb;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Description: zk  注册
 * @Author: mingtian
 * @CreateDate: 2019/9/24 14:52
 * @Version: 1.0
 */
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {

    /**
     * 根目录
     */
    public static final String rootPath = "/eureka";

    /**
     * 订单服务名称
     */
    public static final String orderPath = "/order";

    /**
     * 会员服务名称
     */
    public static final String memberPath = "/member";

    @Value("${server.port:8081}")
    private String port;

    /**
     * 连接地址
     */
    public static final String IP_ADRESS = "127.0.0.1:2181";

    /**
     * 连接超时时间
     * 如果超时时间过短 调试代码的时候会报错（Caused by:org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for）
     */
    public static final int TIMEOUT = 5000;

    /**
     * 计数器
     */
    public static CountDownLatch countDownLatch = new CountDownLatch(1);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        start();
    }

    /**
     * zk 启动
     *
     * @throws IOException
     */
    public void start() throws IOException, KeeperException, InterruptedException {

        ZooKeeper zk = new ZooKeeper(IP_ADRESS, TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                Event.KeeperState state = event.getState();
                if (state == Event.KeeperState.SyncConnected) {
                    System.out.println("zk 连接成功!");
                }

            }
        });

        //判断父节点是否存在
        Stat exists = zk.exists(rootPath, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("判断是否存在父节点:" + event.getState().name());
            }
        });
        //如果父节点不存在，则创建父节点
        if (exists == null) {
            //创建根节点
            String path = zk.create(rootPath, "http://127.0.0.1:8080".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("创建父节点成功:" + path);
        }
        String data = "http://127.0.0.1:" + port;

        String orderUrl = zk.create(rootPath + "/" + port, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("orderUrl:" + orderUrl);
    }

}